import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {tap} from 'rxjs/operators';

import {CacheService} from '../chche/cache.service';

const CACHABLE_URL = 'http://jsonplaceholder.typicode.com';

/**
 * 请求缓存控制器
 */
@Injectable()
export class CacheInterceptor implements HttpInterceptor {

  constructor(private cache: CacheService) {
  }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // 判断当前请求是否可缓存
    if (!this.isRequestCachable(request)) {
      return next.handle(request);
    }
    // 获取请求对应的缓存对象，若存在则直接返回该请求对象对应的缓存对象
    const cachedResponse = this.cache.get(request);
    if (cachedResponse !== null) {
      return of(cachedResponse);
    }
    // 发送请求至 API 站点，请求成功后保存至缓存中
    return next.handle(request).pipe(
      tap(event => {
        if (event instanceof HttpResponse) {
          this.cache.put(request, event);
        }
      })
    );
  }

  // 判断当前请求是否可缓存
  private isRequestCachable(request: HttpRequest<any>) {
    return (request.method === 'GET') && (request.url.indexOf(CACHABLE_URL) > -1);
  }
}
